import { saveFile, deliveryProduct } from '../../../api/index'
const uploadOss = require('../../../utils/upload/uploadImg.js')
import { uuid } from '../../../utils/util'

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    detail: {
      type: Object,
      value: {}
    }
  },
  data: {
    showTypePop: false,
    fileList: [],
    form: {
      type: 2,
      typeStr: '物流配送',
      fileList: []
    },
    currentItem: {},
    columns: [
      { label: '自行配送', value: 1 },
      { label: '物流配送', value: 2 }
    ]
  },
  methods: {
    changeInput ({ currentTarget: { dataset: { key } }, detail: { value } }) {
      this.setData({ ['form.' + key]: value })
    },
    close () {
      this.triggerEvent('close')
    },
    async confirm () {
      try {
        if (this.data.form.type === 1) {
          if (!this.data.form.deliveryDate) {
            wx.showToast({ title: '请选择配送时间！', icon: 'none' })
            return
          }
        } else{
          if (!this.data.form.courierCompany) {
            wx.showToast({ title: '请输入配送公司！', icon: 'none' })
            return
          }
          if (!this.data.form.courierNumber) {
            wx.showToast({ title: '请输入物流单号！', icon: 'none' })
            return
          }
          if (!this.data.form.fileImg) {
            wx.showToast({ title: '请上传物流单照片！', icon: 'none' })
            return
          }
        }
        wx.showLoading({ title: '发货中...', mask: true })
        await deliveryProduct({ ...this.data.form })
        wx.hideLoading()
        wx.showToast({ title: '已确认发货！', icon: 'none' })
        this.triggerEvent('confirm')
      } catch (err) {
        wx.hideLoading()
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    changeDate ({ detail: { value } }) {
      this.setData({ 'form.deliveryDate': value })
    },
    select ({ currentTarget: { dataset: { item } } }) {
      this.setData({ currentItem: item })
    },
    closeTypePop () {
      this.setData({ showTypePop: false })
    },
    async confirmType () {
      if (this.data.currentItem.value === 1) {
        this.data.form = {
          type: this.data.currentItem.value,
          typeStr: this.data.currentItem.label,
          deliveryDate: '',
          orderId: this.data.detail.orderId
        }
      } else {
        this.data.form = {
          type: this.data.currentItem.value,
          typeStr: this.data.currentItem.label,
          courierCompany: '',
          courierNumber: '',
          fileImg: '',
          fileList: [],
          orderId: this.data.detail.orderId
        }
      }
      this.setData({ form: this.data.form, showTypePop: false, currentItem: {} })
    },
    selectType () {
      this.setData({ showTypePop: true })
    },
    deleteFile ({ currentTarget: { dataset: { index } } }) {
      this.data.form.fileList.splice(index, 1)
      this.setData({ 'form.fileList': this.data.form.fileList, 'form.fileImg': '' })
    },
    deleteTempFile ({ currentTarget: { dataset: { index } } }) {
      this.data.fileList.splice(index, 1)
      this.setData({ fileList: this.data.fileList })
    },
    addFile ({ target: { dataset: { key, num } } }) {
      let _this = this
      wx.chooseMedia({
        count: parseInt(num),
        mediaType: ['image'],
        async success (res) {
          wx.showLoading({ title: '上传中...', mask: true })
          res.tempFiles.forEach(item => {
            item.uuid = uuid()
            item.progress = 0
          })
          let tempFiles = res.tempFiles
          let temFileList = []
          if (tempFiles.length) {
            temFileList = await Promise.all(tempFiles.map(async (item, index) => {
              const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
              if (file) {
                const { ResultSet } = await saveFile({
                  fileList: [{
                    fileSize: item.size,
                    fileName: file.fileName,
                    fileUrl: file.fileUrl
                  }]
                })
                let reItem = {
                  uuid: item.uuid,
                  picId: ResultSet.userData.fileIdList[0].fileId,
                  fileName: file.fileName,
                  fileUrl: ResultSet.userData.fileIdList[0].fileUrl,
                  url: ResultSet.userData.fileIdList[0].url,
                }
                return reItem
              } else {
                tempFiles[index].success = 1
                _this.setData({
                  [`${key}`]: tempFiles
                })
              }
            }))
            let tempFileList = temFileList.filter(item => item)
            _this.data.form[key] = tempFileList
            _this.data.form[key].forEach((item) => {
              let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
              if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
            })
            _this.setData({
              [`${key}`]: tempFiles,
              [`form.${key}`]: _this.data.form[key],
              'form.fileImg': _this.data.form[key][0].picId
            })
            wx.hideLoading()
          }
        }
      })
    },
    uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
      return new Promise((resolve, reject) => {
        uploadOss(item[key],
          (res) => {
            resolve(res)
          },
          (err) => {
            wx.hideLoading()
            resolve()
          },
          files, index, that, dataKey
        )
      })
    },
    beforeOpen () {
      this.data.form = {
        orderId: this.data.detail.orderId,
        type: 2,
        typeStr: '物流配送',
        courierCompany: '',
        courierNumber: '',
        fileImg: '',
        fileList: [],
      }
      this.setData({ form: this.data.form })
    }
  },
})